package com.zhiwang.planet.ui.main


import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.ConsoleMessage
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.afollestad.materialdialogs.MaterialDialog
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.tencent.bugly.crashreport.BuglyLog
import com.tencent.bugly.crashreport.CrashReport
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerAccountComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.LoginEvent
import com.zhiwang.planet.event.LogoutEvent
import com.zhiwang.planet.event.NetWorkConnectedEvent
import com.zhiwang.planet.mvp.p.UserPresenter
import com.zhiwang.planet.mvp.v.InviteInfoView
import com.zhiwang.planet.mvvm.model.entity.main.InviteInfo
import com.zhiwang.planet.ui.BaseFragment
import com.zhiwang.planet.ui.FragmentChangeListener
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.util.ShareHelper
import com.zhiwang.planet.util.ShareUtil.ShareHelperSOUL.shareToWeibo
import com.zhiwang.planet.util.Store
import com.zhiwang.planet.util.TokenManager
import com.zhiwang.planet.util.dp
import kotlinx.android.synthetic.main.fragment_friend.*
import kotlinx.android.synthetic.main.invite_dialog_layout.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import javax.inject.Inject


/**
 * A simple [BaseFragment] subclass.
 *
 */
class FriendFragment : BaseFragment(), InviteInfoView {

    private lateinit var statusBarHandler: FragmentChangeListener

    @Inject
    lateinit var userPresenter: UserPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerAccountComponent.builder()
                .accountModule(AccountModule(context as AppCompatActivity))
                .appComponent(getAppComponent())
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        userPresenter.inviteInfoView = this
        EventBus.getDefault().register(this)
    }

    override fun onInviteInfoLoad(inviteInfo: InviteInfo) {
        friendNumber.text = inviteInfo.count
        diamondNumber.text = inviteInfo.num
        smartRefresh?.finishRefresh()
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_friend, container, false)
    }

    val TAG = "FriendFragment"
    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        val settings = friendWebView.webView?.settings
        settings?.javaScriptEnabled = true
        settings?.useWideViewPort = true
        settings?.textZoom = 100
        friendWebView.setRetryListener(::loadUrl)
        friendWebView.webView?.webChromeClient = object : WebChromeClient() {
            override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
                return super.onConsoleMessage(consoleMessage)
            }
        }
        friendWebView.webView?.addJavascriptInterface(this, "android")
        loadUrl()
        smartRefresh.setOnRefreshListener {
            userPresenter.getInviteInfo()
            loadUrl()
        }
    }

    fun loadUrl() {
        friendWebView.webView?.loadUrl(Store.URL_FRIEND_INVITE, webViewHeader())
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initWebView()
        tv_login.setOnClickListener {
            if (TokenManager.isLoginValid().not())
                onAuthExpired()

        }
        inviteImmediately.setOnClickListener {
            showShareDialog()
        }

        load()
    }

    private fun showShareDialog() {

        val rootView = layoutInflater.inflate(R.layout.invite_dialog_layout, null)
        val shareDialog = AlertDialog.Builder(activity!!)
                .setView(rootView)
                .create()
        rootView.findViewById<View>(R.id.closeBtn).setOnClickListener { shareDialog.dismiss() }
        val shareInfo = userPresenter.getShareInfo()
        rootView.findViewById<View>(R.id.share_wechat).setOnClickListener {
            downloadSharePicAndStartShare(shareInfo.img) {
                ShareHelper.create(context!!).shareImgeToWxFriend(shareInfo)
                shareDialog.dismiss()
            }
        }
        rootView.findViewById<View>(R.id.share_timeline).setOnClickListener {
            downloadSharePicAndStartShare(shareInfo.img) {
                ShareHelper.create(context!!).shareImgeToWxTimeLine(shareInfo)
                shareDialog.dismiss()
            }

        }
        rootView.findViewById<View>(R.id.share_qq).setOnClickListener {
            ShareHelper.create(context!!).shareImageToQQFriend(activity!!, shareInfo.imgLocalPath!!, shareInfo.url)
            shareDialog.dismiss()
        }
        rootView.findViewById<View>(R.id.share_SB).setOnClickListener {
            downloadSharePicAndStartShare(shareInfo.img) {
                shareToWeibo(context!!, shareInfo)
                shareDialog.dismiss()
            }
        }
        rootView.findViewById<View>(R.id.share_qqzone).setOnClickListener {
            ShareHelper.create(context!!).shareImageToQQZone(activity!!, shareInfo.imgLocalPath!!, shareInfo.url)
            shareDialog.dismiss()
        }


        rootView.share_qrcode.setOnClickListener {

            val imageView = ImageView(context)

            val frameLayout = FrameLayout(context)

            frameLayout.minimumHeight = 150.dp
            frameLayout.setBackgroundResource(R.color.white)
            imageView.adjustViewBounds = true
            imageView.scaleType = ImageView.ScaleType.FIT_XY

            val lp = FrameLayout.LayoutParams(150.dp, 150.dp)
            lp.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM
            lp.bottomMargin = 10.dp
            frameLayout.addView(imageView, lp)

            Glide.with(this)
                    .load(BuildConfig.BASE_URL + "invite/app_share?uid=${TokenManager.webviewHeaderUserid()}")
                    .listener(object : RequestListener<Drawable> {
                        override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                            shareDialog.dismiss()
                            return false
                        }

                        override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                            return false
                        }

                    })
                    .into(imageView)

            MaterialDialog.Builder(context!!)
                    .backgroundColorRes(R.color.white)
                    .title("邀请好友")
                    .customView(frameLayout, false)
                    .build()
                    .show()
        }

        shareDialog.show()
    }

    private fun load() {
        if (TokenManager.isLoginValid()) {
            userPresenter.getInviteInfo()
            onLogin(LoginEvent())
        } else {
            onLogout(LogoutEvent())
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden.not()) {
            friendWebView.webView?.addJavascriptInterface(this, "android")
            userPresenter.saveShareInfo(context!!.cacheDir)
        }
    }

    private fun downloadSharePicAndStartShare(url: String, function: () -> Unit) {
        val file = File(Environment.getExternalStorageDirectory(), "planetSharePic")

        if (file.exists() && file.length() != 0L) {
            //share
            function.invoke()
        } else {

            FileDownloader.getImpl().create(url)
                    .setPath(file.absolutePath)
                    .setForceReDownload(false)
                    .setListener(object : FileDownloadListener() {
                        override fun warn(task: BaseDownloadTask?) {

                        }

                        override fun completed(task: BaseDownloadTask?) {
                            function.invoke()
                        }

                        override fun pending(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                        }

                        override fun error(task: BaseDownloadTask?, e: Throwable?) {
                            BuglyLog.e("保存分享图片失败", e?.message)
                            CrashReport.postCatchedException(Throwable("保存分享图片失败:" + e?.message))
                        }

                        override fun progress(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                        }

                        override fun paused(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                        }

                    })
                    .start()
        }


    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        statusBarHandler = context as FragmentChangeListener
    }

    @JavascriptInterface
    fun requestLogin() {
        onAuthExpired()
    }

    @Subscribe
    fun onLogin(event: LoginEvent) {
        tv_login.visibility = View.GONE
        ll_friendinfo.visibility = View.VISIBLE
        userPresenter.getInviteInfo()
        friendWebView.webView?.clearHistory()
        initWebView()
        userPresenter.saveShareInfo(context!!.cacheDir)
    }

    @Subscribe
    fun onLogout(event: LogoutEvent) {
        tv_login.visibility = View.VISIBLE
        ll_friendinfo.visibility = View.GONE
        friendWebView.webView?.clearHistory()
        initWebView()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetWorkReconnected(event: NetWorkConnectedEvent) {
        load()
    }

    /**
     * js h5 点击分享，回调使用 原生的分享功能
     */
    @JavascriptInterface
    fun share() {
        activity?.runOnUiThread {
            showShareDialog()
        }
    }

    @JavascriptInterface
    fun openLink(url: String, isExternal: String) {
        when (isExternal) {
            "false" -> WebViewActivity.load(context!!, url)
            "true" -> {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                context!!.startActivity(intent)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


}
